package com.ibeetl.admin.aod.service.excel.task;

import com.ibeetl.admin.aod.entity.AodIndustryData;
import com.ibeetl.admin.aod.util.DateUtils;
import com.ibeetl.admin.aod.util.DbUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * 行业数据的批量插入
 */
public class InsertDataTask implements Callable<Integer> {

    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    protected String tableName;

    protected List<AodIndustryData> aodIndustryDataList;

    protected Connection connection;

    protected String prefix;

    private int defaultStepLength = 10000;

    public InsertDataTask(List<AodIndustryData> aodIndustryDataList, Connection connection, String prefix) {
        this.aodIndustryDataList = aodIndustryDataList;
        this.connection = connection;
        this.prefix = prefix;
    }

    @Override
    public Integer call() {

        log.info("开始插入数据");
        // 开始时间
        Long startTime = (new Date()).getTime();

        PreparedStatement pstm = null;
        String sql = "";
        try {
            connection.setAutoCommit(false);
            StringBuilder suffix = new StringBuilder();
            pstm = connection.prepareStatement("");

            long size = aodIndustryDataList.size();
            long outerCycles = 1;
            if (size >= defaultStepLength) {
                outerCycles = (size % defaultStepLength) == 0 ? (size % defaultStepLength) : (size % defaultStepLength) + 1;
            }

            // 外层循环，总提交事务次数
            outer :
            for (int i = 0; i < outerCycles; i++) {

                suffix = new StringBuilder();

                for (int j = 0; j < defaultStepLength; j++) {
                    int index = i * defaultStepLength + j;
                    if (index >= size) {
                        break outer;
                    }
                    AodIndustryData aodIndustryData = aodIndustryDataList.get(index);
                    // 构建SQL后缀
                    suffix.append("('" + aodIndustryData.getIndustryId() + "',")
                            .append("'" + DbUtil.escapeStr(aodIndustryData.getAccount()) + "',")
                            .append("'" + DbUtil.escapeStr(aodIndustryData.getPhoneNumber()) + "',")
                            .append((null == aodIndustryData.getSendTime() ? "null" : ("'" + DateUtils.formatToDateTime(aodIndustryData.getSendTime()) + "'")) + ",")
                            .append("'" + DbUtil.escapeStr(aodIndustryData.getSendContent()) + "',")
                            .append("'" + DbUtil.escapeStr(aodIndustryData.getStatus()) + "',")
                            .append("'" + DbUtil.escapeStr(aodIndustryData.getReplyContent()) + "',")
                            .append((null == aodIndustryData.getReplyTime() ? "null" : ("'" + DateUtils.formatToDateTime(aodIndustryData.getReplyTime()) + "'")) + ",")
                            .append((null == aodIndustryData.getNumberAttribution() ? "null" : ("'" + aodIndustryData.getNumberAttribution() + "'")) + ",")
                            .append("'" + DbUtil.escapeStr(aodIndustryData.getLabel()) + "',")
                            .append((null == aodIndustryData.getLevel() ? "null" : ("'" + aodIndustryData.getLevel() + "'")) + ",")
                            .append((null == aodIndustryData.getAddTime() ? "null" : ("'" + DateUtils.formatToDateTime(aodIndustryData.getAddTime()) + "'")) + "),");
                }
                // 构建完整SQL
                sql = prefix + suffix.substring(0, suffix.length() - 1);
                // 添加执行SQL
                pstm.addBatch(sql);
                // 清空上一次添加的数据
                suffix = new StringBuilder();
            }
            // 判断是否还有需要执行的SQL
            if (suffix.length() > 0) {
                // 构建完整SQL
                sql = prefix + suffix.substring(0, suffix.length() - 1);
                // 添加执行SQL
                pstm.addBatch(sql);
                // 清空上一次添加的数据
                suffix = new StringBuilder();
            }
            pstm.executeBatch();
            Long endTime = System.currentTimeMillis();
            log.info("插入数据结束,用时" + (endTime - startTime));
        } catch (Exception e) {
            log.error("报错的sql：" + sql);
            throw new RuntimeException(e);
        } finally {
            if(null != pstm){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return 1;
    }
}
